<template>
    <div class="mainContent">
        <path-tracking :path='path' />
        <div class="pageContent">
            <p @click="createBtn" v-if="createBtns" class="createBtn"><img src="@/assets/img/button_plus.png" class="iconPlus" />创建预约</p>
            <!-- 筛选按钮 -->
            <div style="background: #FFF;border-radius: 8px;">
                <filterBtns
                    ref="filterBtns"
                    :configArr="statusConfig"
                    @changingCondition="changingCondition"
                    style="margin-left: 15px;margin-bottom: -10px;"
                />
                <div class="table-title">
                    <div class="table-icon"></div>
                    <div class="table-fl">查询条件</div>
                </div>
                <advanced-search
                    style="margin-top: -10px;"
                    ref="advancedSearch"
                    :option="filterOption"
                    @onClear="onClear"
                    @onSearch="debounceRequest"
                />
            </div>
            <!-- 列表标题&操作按钮 -->
            <el-row style="margin-top: 10px;">
                <div class="common-table-title">
                    <div class="common-table-icon"></div>
                    <div class="common-table-fl">待处理列表</div>
                    <div class="common-btn-group">
                        <div class="operate-btn" v-if="manoeuverIcon" @click="manoeuverBtn">指派</div>
                    </div>
                </div>
            </el-row>
            <el-row style="padding: 0 16px;background: #FFF;border-radius:0 0 8px 8px;">
                <el-table
                    :data="scheduledListData"
                    :row-style="selectedHighlight"
                    max-height="550"
                    ref="recordList"
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column
                        type="selection"
                        width="50"
                        align="center"
                    />
                    <el-table-column
                        v-for='(item, index) in scheduledListItem'
                        :key="index"
                        :prop='item.prop'
                        :label='item.label'
                        :width="item.width"
                        align='center'
                    >
                        <template slot-scope="scope">
                            <div>
                                {{translateData(scope.row, item)}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        label="操作"
                        width="240"
                        align='center'
                    >
                        <template slot-scope="scope">
                            <div class="btnsCan">
                                <div v-if="showDetail" @click="seeDetail(scope.row)" class="operateBtn check">
                                    查看
                                </div>
                                <div @click="clickBtn('edit', scope.row)" class="operateBtn edit" v-if="judgeStatus && editBtn">
                                    编辑
                                </div>
                                <div @click="goVerify('verify', scope.row)" class="operateBtn verify" v-if="judgeStatus && verifyBtn">
                                    审核
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页 -->
                <el-row class="pagination-cont">
                    <el-pagination
                        @size-change="handleSizeChange"
                        background
                        @current-change="handleCurrentChange"
                        :current-page="currentPageIndex"
                        :page-sizes="pageSizeList"
                        :page-size="currentPageSize"
                        layout="total, sizes, prev, pager, next, jumper"
						:pager-count="5"
                        :total="total"
                    />
                </el-row>
            </el-row>
        </div>
        <manoeuver-popup 
            ref="manoeuverPopup"
            :TableSelectData="TableSelectData"
            @refresh="refresh"
        />
    </div>
</template>
<script>
import pathTracking from '@/components/common/pathTracking'
import advancedSearch from '@/components/common/filter/advancedSearch.vue'
import filterBtns from '@/components/common/filterBtnsAuto'
import manoeuverPopup from './manoeuverPopup'
import datas from './datas.js'
// 获取按钮权限配置的方法
import operationConfig from '@/utils/btnsPermission'
import { getPendingOrders, getResource, getCount, editCheck, getFollowUpList } from './axios.js'
export default {
    name: 'bookedCustomer',
    data() {
        return{
            path: ['CRM', '预约管理', '预约审核'],
            // 当前状态
            currentStatus: '',
            currentSearchClue: '',
            // 搜索条件
            filterOption: _.cloneDeep(datas.filterOption),
            // 三种状态的参数
            statusConfig: datas.statusConfig,
            // 当前每页显示的条数
            currentPageSize: 10,
            pageSizeList: [10, 20, 30, 40],
            total: 0,
            // 当前页码
            currentPageIndex: 1,
            // 预约列表项
            scheduledListItem: datas.scheduledListItem,
            // 预约列表内容
            scheduledListData: [],
            // 选中项的数组
            TableSelectData: [],
            timer: null,

            createBtns: false,
            manoeuverIcon: false,
            showDetail: false,
            editBtn: false,
            verifyBtn: false,
        }
    },
    components: {
        pathTracking,
        advancedSearch,
        filterBtns,
        manoeuverPopup
    },
    methods: {
        // 获取数量
        getCount() {
            getCount().then(res => {
                if(res.data.status === 200) {
                    let temp = res.data.result
                    this.statusConfig.map((ele, index) => {
                        ele.count = temp[index + 1]
                    })
                }  
            });
        },
        // 点击搜索
        toSearch(tip) {
            let obj = {}
            obj.type = 1;
            obj.status = 1;
            let val = this.$refs.advancedSearch.getFormData();
            let doSearch = false
            val.map(ele => {
                if(ele.value !== '' && ele.value != undefined) {
                    doSearch = true
                    if(ele.key === 'createTime') {
                        obj.createTimeStart = new Date(ele.value[0]).getTime()
                        obj.createTimeEnd = new Date(ele.value[1]).getTime()
                    }else if(ele.key === 'reservationTime') {
                        obj.reservationStartTimeQuery = new Date(ele.value[0]).getTime()
                        obj.reservationEndTimeQuery = new Date(ele.value[1]).getTime()
                    }else if(ele.key === 'area') {
                        obj.area = ele.value.area
                        obj.shop = ele.value.store
                    }else {
                        obj[ele.key] = ele.value
                    }
                }
            })
            if(!doSearch && tip === 'noTip'){
                this.scheduledListData = []
                this.total = 0
                return
            }
            if(!doSearch) {
                this.$message({
                    message: '请选择查询条件',
                    type: 'warning'
                })
                return
            }
            if(Object.prototype.toString.call(this.currentStatus) === "[object Object]") {
                this.currentStatus.type != undefined && (obj.type = this.currentStatus.type)
                this.currentStatus.value != undefined && (obj.value = this.currentStatus.value)
                this.currentStatus.status != undefined && (obj.status = this.currentStatus.status)
                this.currentStatus.isAssign != undefined && (obj.isAssign = this.currentStatus.isAssign)
                this.currentStatus.followUpBy != undefined && (obj.followUpBy = this.currentStatus.followUpBy)
            }else {
                obj.followUpBy = 1
            }
            let param = {
                condition: obj,
                pageIndex: this.currentPageIndex,
                pageSize: this.currentPageSize,
                pageTotal: 5,
                total: 0
            }
            getPendingOrders(param).then(res => {
                if(res.data.status === 200) {
                    this.scheduledListData = res.data.result.result
                    this.total = res.data.result.total
                }else {
                    this.$message({
                        showClose: true,
                        message: res.data.msg,
                        type: 'error'
                    });
                }
            }).catch(err => {
                this.$message({
                    showClose: true,
                    message: '查询失败',
                    type: 'error'
                });
            });
        },
        onClear() {
            datas.filterOption.items.map(ele => {
                ele.key === 'reservationTime' && (ele.value = undefined)
            })
            this.filterOption = Object.assign({}, datas.filterOption)
        },
        // 获取预约来源
        async getResourceInfo() {
            let res = await getResource();
            getResource().then(res => {
                if(res.status === 200) {
                    let arr = [{
                        label: '请选择预约来源',
                        value: undefined
                    }]
                    res.data.result.map(ele => {
                        let obj = {}
                        obj.value = ele.value
                        obj.label = ele.value
                        arr.push(obj)
                    })
                    this.filterOption.items.forEach(ele => {
                        if(ele.key === 'source') {
                            ele.data = arr
                        }
                    });
                }
            }).catch(err => {
                console.log('err: ', err)
            })
        },
        // 获取跟进人列表
        getFollowUp() {
            getFollowUpList().then(res => {
                if(res.data.status === 200) {
                    let arr = [{
                        label: '请选择创建人',
                        value: undefined
                    }]
                    res.data.result.map(ele => {
                        arr.push({
                            label: ele.userName,
                            value: ele.sapUserId
                        })
                    })
                    this.filterOption.items.map(ele => {
                        ele.key === 'createBy' && (ele.data = arr)
                    })
                }
            }).catch(err => {
                console.log('err: ', err)
            })
        },
        // 创建预约
        createBtn() {
            this.$router.push({path: 'operateOrder', query: {pageType: 'create'}})
        },
        // 查看
        seeDetail(param) {
            this.$router.push({name: 'seeDetail', query: {searchKey: param.id}})
        },
        // 编辑
        clickBtn(type, param) {
            this.$router.push({name: 'editOrder', query: {pageType: type, searchKey: param.id}})
        },
        // 审核
        goVerify(type, param) {
            this.$router.push({name: 'verifyOrder', query: {pageType: type, searchKey: param.id}})
            // console.log(param, 'param')
            // editCheck(param.id).then(res => {
            //     console.log('res:>>>>>>>>', res)
            //     if(res.data.status === 200) {
            //         res.data.result.status === 1
            //         ?
            //         this.$router.push({name: 'verifyOrder', query: {pageType: type, searchKey: param.id}})
            //         :
            //         this.$message({
            //             message: '该预约已被处理',
            //             type: 'warning'
            //         })
            //     }
            // }).catch(err => {
            //     console.log('err: ', err)
            // })
        },
        // 指派
        manoeuverBtn() {
            if(this.TableSelectData.length) {
                let pass = false
                this.TableSelectData.map(ele => {
                    ele.status === 1 && (pass = true)
                })
                pass 
                ? 
                this.$refs.manoeuverPopup.openBox() 
                : 
                this.$message({
                    showClose: true,
                    message: '请选择待审批状态的项目',
                    type: 'warning'
                });
            }else {
                this.$message({
                    showClose: true,
                    message: '请选择待审批状态的项目',
                    type: 'warning'
                });
            }
        },
        // 点击选项卡
        changingCondition(item) {
            this.currentStatus = item;
            // this.toSearch()
        },
        translateData(data, item) {
            let res = ''
            switch (item.prop) {
                case 'regularCustomer':
                    data[item.prop] ? res = '是' : res = '否'
                    break;
                case 'reservationDate':
                    data.reservationStartTime && (res = data['reservationStartTime'].split(' ')[0])
                    break;
                case 'reservationTime':
                    data.reservationStartTime 
                    && data.reservationEndTime 
                    && (res = `${data.reservationStartTime.split(' ')[1]}-${data.reservationEndTime.split(' ')[1]}`)
                    break;
                default: 
                    res = data[item.prop]
                    break;
            }
            return res
        },
        judgeStatus(data) {
            if(data.status == 2 || data.status == 3 || data.status == 4) {
                return false
            }else {
                return true
            }
        },
        // 修改?条/页
        handleSizeChange (size) {
            if(this.currentPageSize != size) {
                this.currentPageSize = size;
                this.debounceRequest();
            }
        },
        // 翻页
        handleCurrentChange (index) {
            if(this.currentPageIndex != index) {
                this.currentPageIndex = index;
                this.debounceRequest();
            }
        },
        // 调用查询接口
        debounceRequest() {
            if(this.timer) {
                clearTimeout(this.timer);
                this.timer = null
            }
            this.timer = setTimeout(() => {
                this.toSearch();
                clearTimeout(this.timer);
                this.timer = null;
            }, 300)
        },
        // 选中的数组
        handleSelectionChange (selection) {
            this.TableSelectData = selection;
        },
        // 如果选中则添加高亮样式
        selectedHighlight (data) {
            if (this.TableSelectData.indexOf(data.row) > -1) {
                return {
                    "background-color": "#FEF6EE"
                };
                return {}
            }
        },
        // 指派成功，刷新数据
        refresh() {
            this.getCount();
            this.toSearch();
        },
        // 按钮权限
        btnsControl() {
            let permission = operationConfig(this.$route);
            this.createBtns = false
            this.manoeuverIcon = false
            this.showDetail = false
            this.editBtn = false
            this.verifyBtn = false
            permission.forEach(ele => {
                if(ele.menu_name === '创建预约') {
                    this.createBtns = true
                }else if(ele.menu_name === '导出') {
                    this.manoeuverIcon = true
                }else if(ele.menu_name === '查看') {
                    this.showDetail = true
                }else if(ele.menu_name === '编辑') {
                    this.editBtn = true
                }else if(ele.menu_name === '审核') {
                    this.verifyBtn = true
                }
            })
        }
    },
    mounted() {
        this.getCount();
        this.getResourceInfo();
        this.getFollowUp(); 
        this.btnsControl();
    },
    activated() {
        this.toSearch('noTip');
    },
    deactivated() {
        // this.filterOption = Object.assign({}, datas.filterOption)
    },
}
</script>
<style scoped>
    .table-title {
        width: 100%;
        height: 58px;
        background-color: #fff;
        border-radius: 8px 8px 0px 0px;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        /* overflow: hidden; */
    }

    .table-title .table-icon {
        width: 6px;
        height: 18px;
        background-color: #7e6b5a;
        float: left;
        margin-left: 19px;
    }

    .table-title .table-fl {
        font-size: 16px;
        color: #222222;
        margin-left: 8px;
    }
    .pageContent{
        padding: 16px;
    }
    .iconPlus{
        width: 12px;
        height: 12px;
        margin-right: 4px
    }
    .createBtn{
        height: 40px;
        width: 100px;
        display: flex;
		align-items: center;
		justify-content: center;
        margin-bottom: 1.5rem;
        background: #7E6B5A;
        color: #FFF;
        text-align: center;
        border-radius: 20px;
        font-size: 14px;
        cursor: pointer;
    }
    .pagination-cont{
        height: 8.8rem;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #fff;
    }
    .btnsCan{
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
    }
    .operateBtn{
        width: 5rem;
        height: 2.4rem;
        cursor: pointer;
        line-height: 2.4rem;
        border-radius: 1.2rem;
        color: #7E6B5A;
        border: 1px solid #7E6B5A;
    }
    /* .check{
        background: #7E6B5A;
        color: #FFF;
    }
    .edit{
        background: #222222;
        color: #FFF;
        border-color: #000;
    } */
    /* .verify{
        color: #7E6B5A
    } */
    .operate-btn {
        padding: 6px 14px;
        display: inline-block;
        border-radius: 14px;
        border: solid 1px #7e6b5a;
        font-family: "Microsoft YaHei","微软雅黑","Microsoft JhengHei","华文细黑",STHeiti,MingLiu,'Avenir', Helvetica, Arial, sans-serif;
        font-size: 14px;
        color: #7e6b5a;
        cursor: pointer;
        line-height: 1;
        margin-right: 1rem;
    }
</style>
